﻿#region 文件信息
/****************************************************************
*	公司名称：福建力和行智能科技有限公司
*   作    者：Jeff
*   CLR 版本：4.0.30319.42000
*   创建时间：1/10/2025 11:54:33 AM
*	用 户 名：zheqichen 
*   描述说明：
*
*   修改历史：
*		1）	修 改 人：
*			修改日期：
*			修改内容：			
*
*****************************************************************/
#endregion

using System.IO;
using System.Windows.Forms;
using static Lhxzn.LangExtractor.AITranslator;

namespace Lhxzn.LangExtractor
{
    /// <summary>
    /// 类    名:ShowAIResponseForm
    /// 描    述:AI翻译操作界面
    /// 修改时间:1/10/2025 11:54:33 AM
    /// </summary>
    public partial class ShowAIResponseForm : Form
    {
        #region 成员变量

        #region private
        /// <summary>
        /// 锁
        /// </summary>
        private readonly object m_lockObject = new object();
        #endregion


        #region protected



        #endregion


        #region public
        /// <summary>
        /// 语言档管理器
        /// </summary>
        public LngFileManager LngFileManager { get; private set; }
        #endregion

        #endregion


        #region 构造函数
        /// <summary>
        /// 函 数 名:构造函数
        /// 函数描述:默认构造函数
        /// 修改时间:1/10/2025 11:54:33 AM
        /// </summary>
        public ShowAIResponseForm(LngFileManager lngFileManager)
        {
            InitializeComponent();
            int screenWidth = Screen.PrimaryScreen.Bounds.Width;
            int screenHeight = Screen.PrimaryScreen.Bounds.Height;
            Width = (int)(screenWidth * 0.9);
            Height = (int)(screenHeight * 0.9);
            StartPosition = FormStartPosition.CenterScreen;
            LngFileManager = lngFileManager;
        }


        #endregion

        #region 父类函数重载、接口实现

        /// <summary>
        /// 关闭页面事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            //e.Cancel = true;
            base.OnFormClosing(e);
        }

        /// <summary>
        /// 加载页面事件，读取配置
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            var appDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string path = Path.Combine(appDirectory, "Config.ini");
            if (File.Exists(path))
            {
                AITranslator.Instance.ApiKey = IniFile.ReadValueFromPath(path, "AIConfig", "ApiKey");
                AITranslator.Instance.commandStr = IniFile.ReadValueFromPath(path, "AIConfig", "commandStr");
                AITranslator.Instance.DeepSeekApiUrl = IniFile.ReadValueFromPath(path, "AIConfig", "DeepSeekApiUrl");
            }
            AITranslator.Reset();
            SetEvents();

        }

        /// <summary>
        /// 页面关闭事件，保存配置
        /// </summary>
        /// <param name="e"></param>
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            var appDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string path = Path.Combine(appDirectory, "Config.ini");
            IniFile.WriteValueToPath(path, "AIConfig", "ApiKey", Instance.ApiKey);
            IniFile.WriteValueToPath(path, "AIConfig", "commandStr", Instance.commandStr);
            IniFile.WriteValueToPath(path, "AIConfig", "DeepSeekApiUrl", Instance.DeepSeekApiUrl);
            CancelEvents();
        }
        #endregion

        #region 函数

        #region private
        /// <summary>
        /// 设置事件
        /// </summary>
        private void SetEvents()
        {
            AITranslator.Instance.AIResponse += OnAIResponse;
            AITranslator.Instance.UserRequest += OnUserRequest;
            lb_SelectChatRecord.SelectedValueChanged += OnClickLBSelectedChatRecord;
            lb_SelectChatRecord.ContextMenuStrip = new ContextMenuStrip();
            lb_SelectChatRecord.ContextMenuStrip.Items.Add(new ToolStripMenuItem("删除", null, OnClickTsbtnDeleteFile));
            //文件导入
            tsmi_InputCurrentPakage.Click += OnClickInputLngPakFromWorkStation;
            tsmi_InputLngFile.Click += OnClickInputLngFile;
            tsmi_InputLngPak.Click += OnClickInputLngPak;
            //文件导出
            tsmi_OutputToDirectory.Click += OnClickOutputToDirectory;
            tsmi_OutputCurrentpak.Click += OnClickOutputCurrentPak;

            tsbtn_Setting.Click += OnClickSetting;
            tsmi_ClearFile.Click += OnClickClearFiles;
            tsmi_OrderFile.Click += OnClickOrderFiles;
        }

        /// <summary>
        /// 导入工作台语言包并翻译
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickInputLngPakFromWorkStation(object? sender, EventArgs e)
        {
            if (LngFileManager.CurrentPackage == null)
            {
                MessageBox.Show("请先导入语言包");
                return;
            }

            Task.Run(() => AITranslator.AnalyzeLanguagePakAsync(LngFileManager.CurrentPackage));
        }

        /// <summary>
        /// 取消事件
        /// </summary>
        private void CancelEvents()
        {
            AITranslator.Instance.AIResponse -= OnAIResponse;
            AITranslator.Instance.UserRequest -= OnUserRequest;
        }

        /// <summary>
        /// 对话记录按照名称排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickOrderFiles(object? sender, EventArgs e)
        {
            lock (m_lockObject)
            {
                AITranslator.Instance.ChatRecords = AITranslator.Instance.ChatRecords.OrderBy(item => item.Name).ToList();
                lb_SelectChatRecord.Items.Clear();
                lb_SelectChatRecord.Items.AddRange(AITranslator.Instance.ChatRecords.ToArray());
            }
        }

        /// <summary>
        /// 删除指定的对话记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickTsbtnDeleteFile(object? sender, EventArgs e)
        {
            lock (m_lockObject)
            {
                object tempt = uc_ShowAIChat.SelectedRecord;
                if(tempt as ChatRecord == null)
                {
                    return;
                }
                AITranslator.Instance.ChatRecords.Remove(tempt as ChatRecord);
                uc_ShowAIChat.SelectedRecord = null;
                RefreshView();
            }
        }

        /// <summary>
        /// 清空对话记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickClearFiles(object? sender, EventArgs e)
        {
            lock (m_lockObject)
            {
                AITranslator.Instance.ChatRecords.Clear();
                uc_ShowAIChat.SelectedRecord = null;
                RefreshView();
            }
        }

        /// <summary>
        /// 输出语言包到指定的文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnClickOutputToDirectory(object? sender, EventArgs e)
        {

            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.Description = "请选择一个文件夹";
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string selectedPath = folderBrowserDialog.SelectedPath;
                Task.Run(() => { AITranslator.SaveChatRecordsToDirectoryAsync(selectedPath); });
            }
        }

        /// <summary>
        /// 设置AI翻译配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickSetting(object? sender, EventArgs e)
        {
            Form form = new Form() {Text="AI翻译参数设置", Height=300,Width=800,StartPosition=FormStartPosition.CenterScreen};
            PropertyGrid grid = new PropertyGrid();
            grid.Dock = DockStyle.Fill;
            grid.SelectedObject = AITranslator.Instance;
            form.Controls.Add(grid);
            form.Show();
        }

        /// <summary>
        /// 导入语言包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickInputLngPak(object? sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.Description = "请选择一个文件夹";
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string selectedPath = folderBrowserDialog.SelectedPath;
                Task.Run(() => AITranslator.AnalyzeFolderAsync(selectedPath)); 
            }
        }

        /// <summary>
        /// 导入语言文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickInputLngFile(object? sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "选择一个语言文件";
            dlg.Filter = "语言文件 (*.lng)|*.lng";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string selectedFilePath = dlg.FileName;
                Task.Run(() => AITranslator.AnalyzeFileAsync(selectedFilePath));
            }
        }

        /// <summary>
        /// 导入当前工作台的语言包
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickOutputCurrentPak(object? sender, EventArgs e)
        {
            if (LngFileManager.CurrentPackage == null)
            {
                MessageBox.Show("请先导入语言包");
                return;
            }

            AITranslator.SaveChatRecordsToLngPak(LngFileManager.CurrentPackage);
        }

        /// <summary>
        /// AI回复事件
        /// </summary>
        /// <param name="record"></param>
        private void OnAIResponse(AITranslator.ChatRecord record)
        {
            lock (m_lockObject)
            {
                RefreshView();
            }
        }

        /// <summary>
        /// 用户询问的事件
        /// </summary>
        /// <param name="record"></param>
        private void OnUserRequest(AITranslator.ChatRecord record)
        {
            lock (m_lockObject)
            {
                RefreshView();
            }
        }

        /// <summary>
        /// 选择对话记录切换的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnClickLBSelectedChatRecord(object? sender, EventArgs e)
        {
            if (lb_SelectChatRecord.SelectedItem as AITranslator.ChatRecord == null)
            {
                return;
            }
            uc_ShowAIChat.SelectedRecord = lb_SelectChatRecord.SelectedItem as AITranslator.ChatRecord;
        }
        #endregion


        #region protected



        #endregion


        #region public
        /// <summary>
        /// 刷新界面
        /// </summary>
        public void RefreshView()
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(() =>
                {
                    RefreshSelectItems();
                    uc_ShowAIChat.RefreshView();
                }));

            }
            else
            {
                RefreshSelectItems();
                uc_ShowAIChat.RefreshView();
            }

        }

        /// <summary>
        /// 刷新选择的项
        /// </summary>
        public void RefreshSelectItems()
        {
            lock (m_lockObject)
            {
                var itemsToAdd = new List<object>();
                var itemsToRemove = new List<object>();
                ChatRecord[] records;
                try
                {
                    //由于异步调用此方法频率特别高，加了锁都会导致资源被多个线程访问，
                    //通过ToArray的方式避免遍历这个列表导致异常
                    records = AITranslator.Instance.ChatRecords.ToArray();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                // 收集需要添加的项目
                foreach (var record in records)
                {
                    if (!lb_SelectChatRecord.Items.Contains(record))
                    {
                        itemsToAdd.Add(record);
                    }
                }

                // 收集需要删除的项目
                foreach (var item in lb_SelectChatRecord.Items)
                {
                    if (!records.Contains(item))
                    {
                        itemsToRemove.Add(item);
                    }
                }

                // 执行添加和删除操作
                lb_SelectChatRecord.Items.AddRange(itemsToAdd.ToArray());
                foreach (var item in itemsToRemove)
                {
                    lb_SelectChatRecord.Items.Remove(item);
                }
            }
        }

        #endregion

        #endregion
    }
}
